
import React from "react";
import FieldContext from "./fieldContext";
/**
 * 字段的组件
 * 类组件是如何获取上下文对象的值呢？
 * 实现双向数据绑定
 * input值显示的是formInstance.store对应的字段的值
 * 当input的值发生改变的时候要把值放到formInstance.store上
 */
class Field extends React.Component<any> {
  public static contextType = FieldContext  //this.context获取Provider里的value

   context!: React.ContextType<typeof FieldContext>
  
  componentDidMount() {
  
    
    this.context.registerField(this);//注册字段的实例
  }
  //组件强制刷新
  onStoreChange = () => {
    this.forceUpdate();
  };

  getControlled = (childProps:any) => {
    const {name} = this.props;
    const {getFieldValue,setFieldsValue} = this.context; //formInstance
    
    return {
      ...childProps,
      value: getFieldValue(name),//这是React属性 React回同步到原生dom上
      onChange: (event:any) => {
        setFieldsValue({[name]: event.target.value});
      }
    };
  };

  render() {
    const { children } = this.props;  //获取原来的儿子  <input placeholder='用户名'/>
    // console.log('children',children);
    //cloneElement这个方法第一个参数是react元素，第二个参数是props方法
    const returnChildNode = React.cloneElement(children, this.getControlled(children.props));
    return returnChildNode;
  }
}
export default Field;



// import React, { useContext, useEffect } from "react";
// import FieldContext from "./fieldContext";
//  const Field = ()=>{
  
//     let context = useContext(FieldContext)
//     useEffect(()=>{
//       context.registerField(this)
//     })
 
//   //组件强制刷新
//   const onStoreChange = () => {
//     this.forceUpdate();
//   };

//  const getControlled = (childProps:any) => {
//     const {name} = this.props;
//     const {getFieldValue,setFieldsValue} = this.context;
//     return {
//       ...childProps,
//       value: getFieldValue(name),
//       onChange: (event:any) => {
//         setFieldsValue({[name]: event.target.value});
//       }
//     };
//   };

 
//     const { children } = this.props;
//     const returnChildNode = React.cloneElement(children, this.getControlled(children.props));
//     return returnChildNode;
  
// }
// export default Field;




